


var getAuthorization = function (options, callback) {


    var url = config.Url;//'../cos/auth?bucket=' + config.Bucket + '&region=' + config.Region;
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.onload = function (e) {
        try {
            var data = JSON.parse(e.target.responseText);
            var credentials = data.credentials;
        } catch (e) {
        }
        callback({
            TmpSecretId: credentials.tmpSecretId,
            TmpSecretKey: credentials.tmpSecretKey,
            XCosSecurityToken: credentials.sessionToken,
            ExpiredTime: data.expiredTime, // SDK 在 ExpiredTime 时间前，不会再次调用 getAuthorization
        });
    };
    xhr.send();



};


function file_md5(file, progress, end){
	var reader = new FileReader(); 
	var blobSlice = File.prototype.mozSlice || File.prototype.webkitSlice || File.prototype.slice;
	//var file = file;
	var chunkSize = 2097152;
	var chunks = Math.ceil(file.size / chunkSize);
	var currentChunk = 0;
	var spark = new SparkMD5();

	reader.onload = function(e) {
		console.log("read chunk nr", currentChunk + 1, "of", chunks);
		spark.appendBinary(e.target.result);
 		                // append binary string
        currentChunk++;
		progress((currentChunk+1)*100/chunks);
		if (currentChunk < chunks) {
			do_load();          
		} else {
			console.log("finished loading");
			end(spark.end());
			//box.val(spark.end());
			console.info("computed hash", spark.end());
			//$("#myprogress").hide()
			// compute hash
		}

	};
	function do_load(){
		var start = currentChunk * chunkSize, end = start + chunkSize >= file.size ? file.size : start + chunkSize;
		reader.readAsBinaryString(blobSlice.call(file, start, end));
	}

    do_load();
                
	
}

let cos = new COS({
    getAuthorization: getAuthorization
});

function file_url(md5) {
    let url = cos.getObjectUrl({
        Bucket: config.Bucket, // Bucket 格式：test-1250000000
        Region: config.Region,
        Key: md5,
        Expires: 60,
        Sign: true,
    }, function (err, data) {
        console.log(err || data && data.Url);
    });
    return url;
}
function file_has(md5, end){
	 cos.headObject({
        Bucket: config.Bucket, // Bucket 格式：test-1250000000
        Region: config.Region,
        Key: md5
    }, function (err, data) {
		console.log(err);
		console.log("data" +data);
        console.log(err ||  data);
		if(data){
			end(true);
		}else{
			//alert('no');
			end(false);
		}
    });
}
function file_upload(md5, file, progress, end){
		//alert(0);
	if (file) {
		//$('#upload').text('正在上传');
		//$("#upload").attr("disabled",true);
		//if(1024 * 1024 * 50 <= file.size){
		//	alert('超过50M的模型，在某些设备上可能会无法运行。')
		//}
        if (file.size > 1024 * 1024) {
		//alert(1);
            cos.sliceUploadFile({
                Bucket: config.Bucket, // Bucket 格式：test-1250000000
                Region: config.Region,
                Key: md5,
                Body: file,
                onTaskReady: function (tid) {
                    TaskId = tid;
                },
                onHashProgress: function (progressData) {
                    console.log('onHashProgress', JSON.stringify(progressData.percent));
                },
                onProgress: function (progressData) {
					//var width = Math.round(progressData.percent*100)+'%';
					//$("#bar").css('width', width);
					//$("#bar_text").text(width);
					progress(progressData.percent*100)
                    console.log('上传中('+Math.round(progressData.percent*100)+'%)');
                },
            }, function (err, data) {

				//$('#uploadform-filename').val(data.Location);
                console.log(err || '上传完成');
				$//('#upload').text('上传完成');
					
				//$("#uploadform-title").attr("disabled",false);
				//$('#w0').submit();

				end();
            });
        } else {
		//alert(2);
            cos.putObject({
                Bucket: config.Bucket, // Bucket 格式：test-1250000000
                Region: config.Region,
                Key: md5,
                Body: file,
                onTaskReady: function (tid) {
                    TaskId = tid;
                },
                onProgress: function (progressData) {
                       
					//var width = Math.round(progressData.percent*100)+'%';
				//	$("#bar").css('width', width);
					//$("#bar_text").text(width);
					
					progress(progressData.percent*100)
                    console.log('上传中('+Math.round(progressData.percent*100)+'%)');
                },
            }, function (err, data) {
                console.log(err);
				//$('#uploadform-filename').val(data.Location);
                console.log(err || '上传完成');
				//$('#upload').text('上传完成');
				//$("#uploadform-title").attr("disabled",false);
				//$('#w0').submit();
				
				end();
            });
        }
    }
}

function files_open(accept, end){
	var input = document.createElement('input');
    input.type = 'file';
    input.accept = accept;
    input.multiple = 'multiple';
    input.onchange = function (e){
        console.log(this.files.length);
		end(this.files);
	};
	
    input.click();
}

function file_compressed(file,progress, end){

    var zip = new JSZip();
    zip.file("MrPP.fbx", file, { date: new Date('September 27, 2016 00:00:01') });
    var  p = 0;
    var interval = setInterval(function(){
        progress(p*100);
        p = p+((0.95-p)/20) *Math.random();
    }, 500);

    zip.generateAsync({type:"Blob",compression: "DEFLATE"}).then(function(content) {
        var f = new File([content], file.name+'.zip',{type: "zip"});
        p=1;
        progress(p*100);
        window.clearInterval(interval)
        end(f);
    });
} 
function file_open(accept, end) {

	var input = document.createElement('input');
    input.type = 'file';
    input.accept = accept;
    input.onchange = function (e){
	
        var file = this.files[0];
		console.log(file);
		end(file);
		
	};
	
    input.click();
//md5.type

}
